package com.kadron.dao;

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.NoResultException;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import com.kadron.entity.Vote;

@AutoCreate
@BypassInterceptors
@Name("voteDAO")
@Scope(ScopeType.EVENT)
public class KVoteDAO extends KDAO<Vote> {

	public Vote find(long userId, long itemId) {
		StringBuffer buffer = new StringBuffer(
				"SELECT v_ FROM Vote v_ WHERE v_.user.id = :user_id AND v_.item.id = :item_id");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("user_id", userId);
		query.setParameter("item_id", itemId);
		try {			
			return (Vote) query.setMaxResults(1).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
	public boolean voted(long userId, long itemId) {
		StringBuffer buffer = new StringBuffer(
		"SELECT 1 FROM Vote v_ WHERE v_.user.id = :user_id AND v_.item.id = :item_id");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("user_id", userId);
		query.setParameter("item_id", itemId);
		try {			
			return query.setMaxResults(1).getSingleResult().equals(1);
		} catch (NoResultException e) {
			return false;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Vote> findItemVotes(long itemId) {
		StringBuffer buffer = new StringBuffer(
		"SELECT v_ FROM Vote v_ WHERE v_.item.id = :item_id");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("item_id", itemId);
		return query.getResultList();
	}
	
	public Number getItemAvgScore(long itemId) {
		StringBuffer buffer = new StringBuffer(
		"SELECT SUM(v_.score),COUNT(v_.id) FROM Vote v_ WHERE v_.item.id = :item_id GROUP BY v_.item.id");
		javax.persistence.Query query = getEntityManager().createQuery(buffer.toString());
		query.setParameter("item_id", itemId);
		try {
			Object[] data = (Object[]) query.setMaxResults(1).getSingleResult();
			Double rating = null;
			if (data != null) {
				Long sum = (Long) data[0];
				Long count = (Long) data[1];
				BigDecimal sumBD = new BigDecimal(sum);
				BigDecimal countBD = new BigDecimal(count);
				rating = sumBD.divide(countBD).doubleValue();
			}
			return rating;
		} catch (NoResultException e) {
			return null;
		}
	}
	
}
